package cn.tedu.cs.controller; 
 /*
 @Time: 2022/8/18 8:51
 @Author:GShuai
 @File:ProductController.class
 @Software:IntelliJ IDEA
*/

import cn.tedu.cs.entity.Product;
import cn.tedu.cs.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
public class ProductController {
    @Autowired(required = false)
    ProductMapper mapper;

    // 读取application.properties 文件中的内容  并赋值给变量
    @Value("G:/files")
    private String dirPath;

    @RequestMapping("/product/insert")
    public void insert(@RequestBody Product product){
        System.out.println("product = " + product);
        // 设置商品的发布时间为当前系统时间
        product.setCreated(new Date());
        mapper.insert(product);
    }

    //商品列的删除操作 先查后删
    @RequestMapping("/product/select")
    public List<Product> select(){
        return mapper.select();
    }

    //删除商品列表
    @RequestMapping("/product/delete")
    public void delete(int id){
        // 通过商品的id查询出商品的图片路径
        String url= mapper.selectUrlById(id);
        // 得到完整的文路径
        String filePath= dirPath+"/"+url;
        // 删除文件
        new File(filePath).delete();
        mapper.deleteById(id);
    }

    @RequestMapping("/product/select/index")
    public List<Product> selectForIndex(){
        return mapper.selectForIndex();
    }

    @RequestMapping("/product/select/top")
    public List<Product>selectTop(){
        return mapper.selectTop();
    }

    @RequestMapping("/product/selectById")
    public Product selectById(int id){
        System.out.println("id = " + id);
        //让浏览量+1
        mapper.updateViewCountById(id);
        return mapper.selectById(id);
    }

    @RequestMapping("/product/selectByCid")
    public List<Product> selectByCid(int cid){
        System.out.println("id = " + cid);
        return mapper.selectByCid(cid);
    }

    @RequestMapping("/product/selectByWd")
    public List<Product> selectByWd(String wd){
        return mapper.selectByWd(wd);
    }

}
